import { defineStore } from "pinia";

// 为 Tab 项定义接口
export interface TabItem {
  name: string;      // 路由名称，用于 keep-alive 缓存
  path: string;      // 路由路径，作为 Tab 的唯一标识
  title: string;     // Tab 标题
  icon?: string;     // Tab 图标 (可选)
  close: boolean;    // Tab 是否可关闭
  isKeepAlive?: boolean; //添加 isKeepAlive 属性
}

// 为面包屑项定义接口
export interface BreadcrumbItem {
  name: string;
  title: string;
}

// Tabs Store
export const useTabsStore = defineStore("TabsStore", {
  state: (): { tabsMenuList: TabItem[] , title: BreadcrumbItem[]  } => ({
    tabsMenuList: [],
    title: []
  }),
  actions: {
    // 添加 Tab
    async addTabs(tabItem: TabItem) {
      const findIndex = this.tabsMenuList.findIndex(item => item.path === tabItem.path);

      if (findIndex !== -1) {
        // 如果 Tab 已存在，则用新信息覆盖旧信息
        // 这确保了 isKeepAlive 等 meta 数据可以被更新
        this.tabsMenuList[findIndex] = { ...this.tabsMenuList[findIndex], ...tabItem };
      } else {
        // 如果 Tab 不存在，则添加
        this.tabsMenuList.push(tabItem);
      }
    },

    // 移除 Tab
    removeTabs(tabPath: string, isCurrent: boolean = true): string | undefined {
      const tabs = this.tabsMenuList;
      let nextPath: string | undefined = undefined;

      // 如果要关闭的是当前活动的 Tab，计算出下一个要跳转的路径
      if (isCurrent) {
        const currentIndex = tabs.findIndex(item => item.path === tabPath);
        if (currentIndex !== -1) {
          const nextTab = tabs[currentIndex + 1] || tabs[currentIndex - 1];
          if (nextTab) {
            nextPath = nextTab.path;
          }
        }
      }

      // 过滤掉要关闭的 Tab
      this.tabsMenuList = tabs.filter(item => item.path !== tabPath);

      // 返回下一个路径，让组件去执行跳转
      return nextPath;
    },

    // 关闭多个 Tab (例如：关闭其他、关闭所有)
    async closeMultipleTabs(keepPath?: string) {
      this.tabsMenuList = this.tabsMenuList.filter(item => {
        // 如果是固定不可关闭的 Tab，或者是要保留的 Tab，则保留
        return !item.close || (keepPath && item.path === keepPath);
      });
    },

    // 设置 Tabs (例如：从持久化存储中恢复)
    async setTabs(tabsMenuList: TabItem[]) {
      this.tabsMenuList = tabsMenuList;
    },

    // 更新 Tab 标题 (例如：页面标题是动态的 /:id)
    async setTabTitle(path: string, title: string) {
      const tab = this.tabsMenuList.find(item => item.path === path);
      if (tab) {
        tab.title = title;
      }
    },

    setTitle(title: BreadcrumbItem[]) {
      this.title = title;
    }
  },

  persist: {
    key: "TabsState",
    storage: localStorage,
  },
});

// Setting Store (用于面包屑等)
export const useSettingStore = defineStore('SettingStore', {

});
